package com.shtb.wisdom.videotaker

import android.os.Build
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.internal.userAgent
import java.io.File
import java.io.IOException
import java.util.HashMap

open class VideoTakerService {

    fun recordVideoUpload(fileUrl: String, completion: Callback) {

        var url = "$serviceRootUrl/fileserver/v1/uploadFile"

        upload(fileUrl, url,null, object : Callback {

            override fun onFailure(call: Call, e: IOException) {

                completion.onFailure(call, e)
            }

            override fun onResponse(call: Call, response: Response) {

                completion.onResponse(call, response)
            }
        })
    }


    fun upload(fileUrl: String, url: String, headers: HashMap<String, String>?=null, complete: Callback) {

        val header = headers ?: hashMapOf()

        header["Content-Type"] = "multipart/form-data"

        val mediaType = "video/mp4".toMediaType()

        val fileBody = File(fileUrl).asRequestBody(mediaType)

        val requestBody = MultipartBody.Builder().setType(MultipartBody.FORM)
            .addFormDataPart("file", "record.mp4", fileBody)
            .addFormDataPart("Content-Type","multipart/form-data")
            .build()

        var requestBuilder = Request.Builder().url(url).post(requestBody)

        requestBuilder = addCommonHeaders(requestBuilder, header)

        client.newCall(requestBuilder.build()).enqueue(object : Callback {

            override fun onFailure(call: Call, e: IOException) {

                complete.onFailure(call, e)
            }

            override fun onResponse(call: Call, response: Response) {

                complete.onResponse(call, response)
            }
        })
    }

    /// 向请求添加统一请求头（UA、AccessToken...）
    private fun addCommonHeaders(request:Request.Builder, customHeaders: HashMap<String, String>? = null): Request.Builder {

        // 自定义头
        request.headers(hasMap2RequestHeaders(customHeaders).build())

        // 公共头 —— 统一UA
        val userAgent = userAgent +
                " ${BuildConfig.UserAgent}/${BuildConfig.VERSION_NAME}" +
                " (${BuildConfig.kAppCode}; Android/${Build.VERSION.RELEASE};" +
                " ${Build.BRAND}/${Build.MODEL})"

        request.removeHeader("User-Agent").addHeader("User-Agent", userAgent)

        return request
    }

    /// 将字典头转换成请求头
    private fun hasMap2RequestHeaders(hashMap: HashMap<String, String>?): Headers.Builder {

        val header = Headers.Builder()

        hashMap?.let {

            for (key in it.keys) {

                it[key]?.let { value->

                    header.add(key, value)
                }
            }
        }

        return header
    }

    private val client = OkHttpClient()

    val serviceRootUrl = BuildConfig.ServicesRootUrl + "/${BuildConfig.kApiKey}/${BuildConfig.kApiRouteName}"
}